<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                              |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: anguolei@clcw.com.cn                                           |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\CarResource;

use AuctionBack\Logic\RefundLogic;
use AuctionCore\CarResource\CarModel;
use AuctionCore\Other\Address;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\Finance\CarOwnerCompensate;
use AuctionCore\Finance\ReceivableRefund;
use AuctionCore\PurchaseOrder\PurchaseOrder;
use AuctionBack\Logic\RecheckLogic;

/**
 * 违约车辆
 *
 * @author Angl
 */
class BreachCar
{
    private $modal = null;
    private $car_id = null;

    public function __construct($car_id)
    {
        $this->car_id = $car_id;
        $this->modal = M('breach_car');
    }

    /**
     * 新增违约车辆
     *
     * @param $data
     *
     * @return mixed
     */
    public static function create($data)
    {
        if ($data['car_id'] < 1) {
            return false;
        }
        $data['sid'] = M("cars")->where(['car_id'=>$data['car_id']])->getField("sid");
        $data['create_time'] = date('Y-m-d H:i:s');
        $res = M('breach_car')->add($data);
        return $res;
    }

    /**
     * 更新信息
     *
     * @param $order_id
     * @param $data
     *
     * @return
     */
    public function update($data, $bc_id)
    {
        if ($this->car_id < 1 || empty($data)) return false;
        $map = array();
        $map['car_id'] = array('eq', $this->car_id);
        $map['bc_id'] = array('eq', $bc_id);
        $result = M('breach_car')->where($map)->save($data);
        // echo M()->getLastSql();
        return $result;
    }

    /**
     * 获取详细信息
     *
     * @param $car_id
     *
     * @return bool|mixed
     */
    public function detail()
    {
        if (intval($this->car_id) < 1) return false;
        return M('breach_car')->where("car_id=" . $this->car_id)->find();
    }

    /**
     * 获取详细信息
     *
     * @param $car_id
     *
     * @return bool|mixed
     */
    public function iss_detail($bc_id)
    {
        if (intval($this->car_id) < 1) return false;
        return M('breach_car')->where(array('bc_id' => $bc_id))->find();
    }

    /**
     * 获取违约车辆详情
     *
     * @return bool
     */
    public function breach_car_info($bc_id)
    {
        if (intval($this->car_id) < 1) return false;
        $cols = 'bc.bc_id,bc.status,bc.remark,bc.dealer_name,bc.dealer_phone,bc.trade_price,bc.take_car_man,bc.compensate_type,bc.compensate,bc.breach_type,bc.mid,
               bc.order_id,bc.transfer_fee,bc.deal_time,bc.d_order_id,bc.report_type,
               c.car_id,c.sid,c.sno,c.brand_id,c.series_id,c.model_id,c.car_color,c.emission,c.plate_prefix,c.pointer_mileage,c.three_in_one,c.car_source,
               c.plate_prefix,c.plate_suffix,c.car_color,c.composite_state,c.accident_level,c.car_status,c.reserve_price,
               c.car_no,c.emission,c.first_reg_date,c.pointer_mileage,c.reg_city,c.vin,c.transfer_limit,c.location_area,c.pay_status,c.first_money,c.tail_money,
               co.seller_name,co.phone as seller_phone,co.comefrom,co.owner_type,co.contact_person,e.real_name as checker_name,e.mobile as checker_phone,
               pl.emp_id,pl.pay_type,pl.fid,pl.status as pl_pay_status,pl.last_update as pay_time,
               co.owner_id,c.is_dealer_breach,bc.issue_id,bc.back_method,bc.bank_account';
        $map = array();
        $map['bc.bc_id'] = ['eq', $bc_id];
        $map['bc.car_id'] = ['eq', $this->car_id];
        $prefix = C('DB_PREFIX');
        $detail = M('breach_car')->alias('bc')->field($cols)
	        //->join($prefix . "order as o ON bc.order_id = o.order_id")
            ->join($prefix . "cars as c ON c.car_id = bc.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id=c.owner_id")
            ->join($prefix . "employee as e ON e.emp_id=co.checker_id")
            ->join("LEFT JOIN " . $prefix . "pay_log as pl ON bc.car_id=pl.car_id")
            ->where($map)
            ->find();
        $cm = new CarModel();
	    if($detail['order_id']){
		    $orderObj = new AuOrder($detail['order_id']);
		    $orderDetail = $orderObj->detail();
		    $detail['order_no'] = $orderDetail['order_no'];
		    $detail['order_info'] = $orderDetail;
	    }

	    if($detail['d_order_id']){ //订单信息
		    $orderObj = new AuOrder($detail['d_order_id']);
		    $orderDetail = $orderObj->detail();
		    $detail['d_order_no'] = $orderDetail['order_no'];
		    $detail['d_order_info'] = AuOrder::sortOrderStatus($orderDetail);
	    }

	    $sid = $detail['sid'];
	    $purchaseObj = new PurchaseOrder();
	    $purchaseInfo = $purchaseObj->viewBySid($sid); // 获取采购单信息
	    $detail['purchase_order_nu'] = $purchaseInfo['purchase_order_nu'];


        $brand = $cm->get_model_by_id($detail['brand_id'], 'brand');
        $series = $cm->get_model_by_id($detail['series_id'], 'series');
        $model = $cm->get_model_by_id($detail['model_id']);
        $detail['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $detail['car_color'] = C('CAR_COLOR.' . $detail['car_color']);
        $detail['emission'] = C('INT_EMISSION_STD.' . $detail['emission']);
        $detail['plate_prefix'] = C('PLATE_PREFIX.' . $detail['plate_prefix']);
        $detail['pointer_mileage'] = formatMileage($detail['pointer_mileage']);
        $detail['transfer_limit_str'] = C('TRANSFER_LIMIT.' . $detail['transfer_limit']);
	   // print_r($detail['comefrom']);die();
        $comefrom = M("come_from")->alias('a')->field("a.from_name,b.from_name as parent_name")
            ->join("LEFT JOIN " . $prefix . "come_from as b ON a.pid=b.from_id")
            ->where("a.from_id = " . $detail['comefrom'])->find();
	    //echo "trtr";die();

        $detail['channel_id'] = $detail['comefrom'];
        $detail['comefrom'] = $comefrom['parent_name'] . "-" . $comefrom['from_name'];
        $addr = new \AuctionCore\Other\Address();

        $detail['first_reg_city'] = $addr->get_name_by_code($detail['reg_city']);
        $detail['location_area_code'] = $detail['location_area']; //所在地code
        $detail['location_area'] = $addr->get_name_by_code($detail['location_area']);

        $pay_status = $detail['pay_status'];

	    if ($pay_status == 1) {           //待付首款
		    $detail['pay_status_name'] = "待付首款";
	    } elseif ($pay_status == 2) {     //已付首款
		    $detail['pay_status_name'] = "已付首款";
	    } elseif ($pay_status == 3) {  //待付尾款
		    $detail['pay_status_name'] = "待付尾款";
	    }

	    //echo $detail['pay_status_name'];die();
	    if($detail['car_source']==1){
		    $rate = "100%";
	    }elseif ($detail['car_source']==2){
		    $rate = $detail['three_in_one'] == 1 ? '50%' : '0%' ;
	    }
	    $detail['pay_status_name'] = $detail['pay_status_name'].$rate;
	    //付款人
	    if ($pay_status > 1) {
		    $paymentData = Car::getFirstPaymentBySid($detail['sid']);
		    $detail['pay_man'] = $paymentData['emp_name'];
		    $detail['pay_time'] = $paymentData['update_time'];
	    }else{
		    $detail['pay_man'] = "--";
		    $detail['pay_time'] = "--";
	    }

       /* $order_id = M('order')->where('car_id =' . $this->car_id)->max('order_id');
        $detail['order_id'] = $order_id;*/
        $map = array();
        $map['issue_id'] = array('eq', $detail['issue_id']);
        $dealer_issue = M('dealer_issue')->where($map)->find();
        if ($dealer_issue) {
            $detail['cut_down_price'] = $dealer_issue['cut_down_price'];
            $detail['issue_emp_id'] = $dealer_issue['emp_id'];
            $emp_name = M('employee')->where('emp_id = ' . $detail['issue_emp_id'])->find();
            $detail['emp_name'] = $emp_name['real_name'];
            $detail['issue_remark'] = $dealer_issue['remark'];
            $detail['createtime'] = $dealer_issue['createtime'];
        }

        if ($detail['car_source'] == 1 && !empty($detail['bank_account'])) {
            $bank_account = json_decode($detail['bank_account'], true);
            $detail['bank_name'] = $bank_account['bank_name'];
            $detail['card_no'] = $bank_account['card_no'];
            $detail['account_name'] = $bank_account['account_name'];
        }
        //平台确认备注
        if ($detail['breach_type'] == 1) {
        	if($detail['order_id']){
		        $AuOrder = new AuOrder($detail['order_id']);
		        $platform_confirm_log = $AuOrder->get_platform_confirm_log(['result' => 4]);
		        $detail['platform_confirm_remark'] = $platform_confirm_log['remark'];
	        }else{//旧数据中没有 order_id
		        $order_id = M('order')->where('car_id =' . $this->car_id)->max('order_id');
		        //$detail['order_id'] = $order_id;
		        $AuOrder = new AuOrder($order_id);
		        $platform_confirm_log = $AuOrder->get_platform_confirm_log(['result' => 4]);
		        $detail['platform_confirm_remark'] = $platform_confirm_log['remark'];
	        }
        }
        $detail['owner_type_name'] = C('OWNER_TYPE_NAME')[$detail['owner_type']];

	    if($detail['status'] == 2){ //如果是已退车
		    $refundInfo = RefundLogic::getRefundCarByRefer($bc_id,1);
		    $detail['remark_amount_of_car'] = $refundInfo['remark_amount_of_car'];
		    $detail['remark_payment'] = $refundInfo['remark_payment'];
		    $detail['collection_id'] = $refundInfo['collection_id'];
		    $detail['collection_id_car'] = $refundInfo['collection_id_car'];
		    $detail['payment_id'] = $refundInfo['payment_id'];
		    $detail['back_reason'] = $refundInfo['back_reason'];
	    }
        return $detail;
    }


    /**
     * 获取列表
     *
     * @param $page
     * @param $limit
     * @param $params [$status, $location_area, $order_no, $checker, $driver, $driver_phone]
     *
     * @return array
     */
    public static function get_list($page, $limit, $params = array())
    {
        $page = intval($page) > 0 ? intval($page) : 1;
        $limit = intval($limit) > 0 ? intval($limit) : 10;
        $map = [];
        $map['bc.status'] = intval($params['status']);
        //车辆所在地
        if (!empty($params['location_area'])) {
            $map['c.location_area'] = array('in', $params['location_area']);
        }
        //车辆编号
        if (!empty($params['sno'])) {
            $map['c.sno'] = $params['sno'];
        }
        //付款状态
        $pay_status = $params['pay_status'];
        if ($pay_status == 2) {
            $map['_string'] = 'c.pay_status = 2 OR (c.pay_status = 3 AND c.three_in_one = 2)';
        } elseif ($pay_status == 1) {
            $map['c.pay_status'] = ['eq', $pay_status];
        }
        $cols = "c.car_id,c.car_no,c.location_area,c.brand_id,c.series_id,c.model_id,c.plate_prefix,c.plate_suffix
            ,c.pay_status,c.car_source,c.three_in_one,c.first_money,c.tail_money,c.sid,c.sno,
            co.seller_name,co.phone,
            bc.bc_id,bc.create_time,bc.deal_time,bc.status,bc.issue_id,bc.compensate_type,bc.d_order_id";
        $prefix = C("DB_PREFIX");
        $total = M('breach_car')->alias("bc")
            ->join($prefix . "cars as c ON c.car_id=bc.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id=c.owner_id")
            ->where($map)->count();

        $list = M('breach_car')->alias("bc")->field($cols)
            ->join($prefix . "cars as c ON c.car_id=bc.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id=c.owner_id")
            ->where($map)->page($page)->limit($limit)->select();


        // echo M()->_sql();
        if (!empty($list)) {
            $cm = new CarModel();
            $addr = new Address();
            foreach ($list as $key => $vl) {
				if($vl['status'] == 3){
					$dOrderId = $vl['d_order_id'];
					if($dOrderId){
						$orderObj = new AuOrder($dOrderId);
						$orderDetail = $orderObj->detail();
						$list[$key]['d_order_info'] = AuOrder::sortOrderStatus($orderDetail);
					}else{
						$list[$key]['d_order_info']['status_name'] = '';
						$list[$key]['d_order_info']['order_no'] = '';
					}
				}
                //车型
                $brand = $cm->get_model_by_id($vl['brand_id'], 'brand');
                $series = $cm->get_model_by_id($vl['series_id'], 'series');
                $model = $cm->get_model_by_id($vl['model_id']);
                $list[$key]['car_model'] = $brand['name'] . $series['name'] . $model['name'];
                //所在地
                if ($vl['location_area']) {
                    $location_area = $addr->get_name_by_code($vl['location_area']);
                    $list[$key]['location_area'] = $location_area;
                } else {
                    $list[$key]['location_area'] = '无';
                }
                //车牌号
                $list[$key]['plate_number'] = C("PLATE_PREFIX." . $vl['plate_prefix']) . $vl['plate_suffix'];

	            //付款状态
	            $pay_status = $vl['pay_status'];
	            $list[$key]['pay_status_name'] = C('ORDER_PAY_STATUS')[$pay_status];

	            if($vl['car_source'] == 1){
		            $rate = "100%";
	            }elseif ($vl['car_source'] == 2){
		            $rate = $vl['three_in_one'] == 1 ? '50%' : '0%' ;
	            }
	            if($pay_status == 0){ // 如果未付的就只显示 --，不显示百分比
		            $list[$key]['pay_status'] = $list[$key]['pay_status_name'];
	            }else{
		            $list[$key]['pay_status'] = $list[$key]['pay_status_name'].$rate;
	            }
            }
        }
        $data = ['total' => $total, 'list' => $list];
        return $data;
    }


    /**
     *退车流程
     *如果是我方违约 1平台责任 判断是否付过车主款？ 是--->应收退款-补偿款  否--->直接补偿车主款  2车主原因  是否付过车主款？是-->应收退款+扣款  否-->不记录
     *      车商违约   判断是否付过车主款？ 是--->应收退款-补偿款  否--->直接补偿车主款
     **/
    public function is_compensate_Pay($is_pay = array())
    {
        $res = true;
        //退车类型（1、我方违约 - 赔偿 2、车商违约 - 扣除）
        if ($is_pay['compensate_type'] == 2) {
            if ($is_pay['pay_status'] > 1 && ($is_pay['car_source'] == 1 || ($is_pay['car_source'] == 2 && $is_pay['three_in_one'] == 1))) {
                //付过车主款  应收款=已付金额-赔偿金额  插入应收退款表中
                $Params = array(
                    'owner_id' => $is_pay['owner_id'],
                    'order_id' => $is_pay['order_id'],
                    'car_id' => $is_pay['car_id'],
                    'receivable_type' => 1,
                    'createtime' => date('Y-m-d h:i:s')
                );
                $ReceivableRefund = new ReceivableRefund();
                $res = $ReceivableRefund->add_receivable_refund($Params);
            } else {
                //没有付过车主款   插入车主补偿表
                $Params = array(
                    'owner_id' => $is_pay['owner_id'],
                    'order_id' => $is_pay['order_id'],
                    'car_id' => $is_pay['car_id'],
                    'compensate_amount' => $is_pay['compensate']
                );
                $CarOwnerCompensate = new CarOwnerCompensate();
                $res = $CarOwnerCompensate->add_car_owner_compensate($Params);
            }
            if ($res === false) {
                \Think\Log::record('车商违约退车失败！car_id:' . $is_pay['car_id'] . ',emp_id:' . $is_pay['emp_id']);
                return false;
            } else {
                return true;
            }
        } elseif ($is_pay['compensate_type'] == 1) {
            //检测失误 平台责任 ->补偿
            if ($is_pay['back_method'] == 1) {
                if ($is_pay['pay_status'] > 1 && ($is_pay['car_source'] == 1 || ($is_pay['car_source'] == 2 && $is_pay['three_in_one'] == 1))) {
                    $Params = array(
                        'owner_id' => $is_pay['owner_id'],
                        'order_id' => $is_pay['order_id'],
                        'car_id' => $is_pay['car_id'],
                        'receivable_type' => 1,
                        'createtime' => date('Y-m-d h:i:s')
                    );
                    $ReceivableRefund = new ReceivableRefund();
                    $res = $ReceivableRefund->add_receivable_refund($Params);
                } else {
                    $Params = array(
                        'owner_id' => $is_pay['owner_id'],
                        'order_id' => $is_pay['order_id'],
                        'car_id' => $is_pay['car_id'],
                        'compensate_amount' => $is_pay['compensate']
                    );
                    $CarOwnerCompensate = new CarOwnerCompensate();
                    $res = $CarOwnerCompensate->add_car_owner_compensate($Params);
                }
            } else {
                //车主原因  付过车主款 应收款=已付金额-扣除金额  插入应收退款表中
                $Params = array(
                    'owner_id' => $is_pay['owner_id'],
                    'order_id' => $is_pay['order_id'],
                    'car_id' => $is_pay['car_id'],
                    'receivable_type' => 2
                );
                $ReceivableRefund = new ReceivableRefund();
                $res = $ReceivableRefund->add_receivable_refund($Params);
            }
            if ($res === false) {
                \Think\Log::record('我方违约退车失败！car_id:' . $is_pay['car_id'] . ',emp_id:' . $is_pay['emp_id']);
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    /**
     * 获取违约车辆退车信息
     *
     */
    public function get_breach_car_refund()
    {
        if (intval($this->car_id) < 1) return false;
        $map['car_id'] = ['eq', $this->car_id];
        $map['status'] = ['eq', 2];
        $cols = 'bc_id,emp_id as bc_emp_id,compensate,remark as bc_remark,deal_time';
        return M('breach_car')->field($cols)->where($map)->find();
    }

    /**
     * 根据变更号，获取违约车辆信息
     *
     * @param $mid
     * @return mixed
     */
    public static function BreachCarByMid($mid)
    {
        return M('breach_car')->where(['mid' => $mid])->find();
    }

    //关闭违约车辆
    public static function updateBreachCar($data, $bc_id)
    {
        return M('breach_car')->where(['bc_id' => $bc_id])->save($data);
    }


    /**
     * 根据订单号，获取违约车辆信息
     *
     * @param $orderId
     * @return mixed
     */
    public static function getBreachCarByOrderId($orderId)
    {
        return M('breach_car')->where(['order_id' => $orderId])->find();
    }

    /**
     * 根据订单ID获取违约车辆信息
     * @param $orderId
     * @return mixed
     */
    public static function getInfoByOtherOrderId($orderId)
    {
        $map = [
            'status' => 3,
            'd_order_id' => $orderId
        ];
        return M("breach_car")->where($map)->find();
    }

    /**
     * 添加违约车辆付款单信息
     *
     * @param $data
     * @return mixed
     */
    public function addBreachCarPayment($data)
    {
        return M('au_breach_payment')->add($data);
    }

    /**
     * 添加违约车辆付款单信息
     *
     * @param $data
     * @return mixed
     */
    public function addBreachCarCollection($data)
    {
        return M('au_breach_collection')->add($data);
    }
}

//end class
